package com.paipaideli.common.base;

import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.WindowManager;

import com.paipaideli.common.utils.LogUtil;

import java.util.LinkedList;
import java.util.Queue;

import io.reactivex.disposables.Disposable;

public abstract class BasePresenterFragment extends Fragment implements BasePresenterView {

    protected final String TAG = this.getClass().getSimpleName();

    public abstract void initView();//查询view

    private Queue<Disposable> disposableQueue;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
        disposableQueue = new LinkedList<>();
        if (this instanceof IEventBus) {
            EventBusDelegate.register(this);
        }
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
    }

    @Override
    public void onDestroyView() {
        if (disposableQueue != null && disposableQueue.size() > 0) {
            while (disposableQueue.size() > 0) {
                try {
                    disposableQueue.poll().dispose();
                } catch (Throwable e) {
                    LogUtil.d(e);
                }
            }
        }
        super.onDestroyView();
        if (this instanceof IEventBus) {
            EventBusDelegate.unregister(this);
        }
    }

    @Override
    public AppCompatActivity getCurrentActivity() {
        if (getActivity() instanceof AppCompatActivity) {

            return ((AppCompatActivity) getActivity());
        } else if (getActivity() == null) {

            throw new RuntimeException("Activity not attached");
        }
        return (AppCompatActivity) getActivity();
    }

    @Override
    public void addDisposable(Disposable disposable) {
        if (disposableQueue != null) {
            disposableQueue.add(disposable);
        }
    }

}
